-- Sync time with some servers from the NTP pool 
--and print the result, or that it failed

ntp = {}

function ntp.set_ntp(x)
    if x > 20 then
        print('Error: set_ntp timeout')
        return 0
    end

    if wifi.sta.status() ~= wifi.STA_GOTIP then
        print('wifi is not ready, wait 3s...')
        tmr.create():alarm(1000*3, tmr.ALARM_SINGLE, function()
            ntp.set_ntp(x + 1)
        end)
    else
        print('Setting ntp...')
        sntp.sync({ 'cn.pool.ntp.org',
                    'ntp.aliyun.com',
                    'ntp1.aliyun.com',
                    'ntp2.aliyun.com',
                    'ntp3.aliyun.com',
                    'ntp4.aliyun.com',
                    'ntp5.aliyun.com',
                    'ntp6.aliyun.com',
                    'ntp7.aliyun.com',
                    'ntp.ntsc.ac.cn'},
          function(sec, usec, server, info)
            --print('sync', sec, usec, server)
            rtctime.set(sec+28800, usec)    --28800 东八区
            local tm = rtctime.epoch2cal(rtctime.get())
            print(string.format("date: %04d/%02d/%02d %02d:%02d:%02d", tm["year"], tm["mon"], tm["day"], tm["hour"], tm["min"], tm["sec"]))
          end,
          function()
           print('NTP set failed!')
          end
        )
    end
end

function ntp.get_tim_str()
    local tm = rtctime.epoch2cal(rtctime.get())
    return string.format("%04d/%02d/%02d %02d:%02d:%02d", tm["year"], tm["mon"], tm["day"], tm["hour"], tm["min"], tm["sec"])
end

function ntp.get_tim_str2()
    local ymd, hms
    local tm = rtctime.epoch2cal(rtctime.get())
    ymd = string.format("%04d/%02d/%02d", tm["year"], tm["mon"], tm["day"])
    hms = string.format("%02d:%02d:%02d", tm["hour"], tm["min"], tm["sec"])

    return ymd, hms
end

return ntp
